from es import exists, playsound, getplayersteamid
from cmdlib import registerSayCommand, unregisterSayCommand
from gamethread import delayed
from popuplib import easymenu
from superdice.superdice import players, rollAmount, rollCallback, info
from superdice.libs.diceConfigs import configFile
from superdice.libs.playerStrings import stringsManager
from superdice.libs.dataManager import dataManager

def autoCallback(userid, args):
    steamid = getplayersteamid(userid)
    if not steamid in database:
        database[steamid] = 0
    createPopup(userid, steamid)

def popupCallback(userid, choice, popup):
    steamid = getplayersteamid(userid)
    if choice == 'add':
        if database[steamid] < int(rollAmount):
            database[steamid] += 1
            playsound(userid, 'buttons/combine_button1.wav', 1.0)

        else:
            strings.tellString(userid, 'noadd', {})
            playsound(userid, 'buttons/button11.wav', 1.0)

    elif choice == 'remove':
        if database[steamid] > 0:
            database[steamid] -= 1
            playsound(userid, 'buttons/combine_button2.wav', 1.0)

        else:
            strings.tellString(userid, 'noremove', {})
            playsound(userid, 'buttons/button11.wav', 1.0)

    createPopup(userid, steamid)

def createPopup(userid, steamid):
    popup = easymenu('_superdice_autoroll_' + str(userid), None, popupCallback)
    popup.c_titleformat = strings.getString(userid, 'automenu', {'version':info.version, 'autorolls':database[steamid], 'maxrolls':rollAmount})
    popup.c_beginsep = ' \n '
    popup.c_pagesep = ' \n '
    popup.addoption('add', strings.getString(userid, 'addroll', {}))
    popup.addoption('remove', strings.getString(userid, 'removeroll', {}))
    popup.send(userid)

def causeRoll(userid, steamid):
    while players[userid]['rolls'] < int(rollAmount) and players[userid]['rolls'] < database[steamid]:
        rollCallback(userid, {})

def round_end(ev):
    database.saveDatabase()

def player_spawn(ev):
    if not ev['es_userteam'] in ('2', '3'):
        return
    
    steamid = ev['es_steamid']    
    if not steamid in database:
        database[steamid] = 0

    delayed(0.2, causeRoll, (ev['userid'], steamid))

def unload():
    database.saveDatabase()
    for command in autoCommands:
        if not exists('saycommand', command):
            continue
        unregisterSayCommand(command)

configData = configFile('addon_autoroll')
autoCommands = str(configData.cvar('superdice_cfg_autoroll_autocommands', '!autortd,autortd,!autoroll,autoroll', 'What commands are used?')).split(',')
configData.write()
configData.execute()
for command in autoCommands:
    if exists('saycommand', command):
        continue
    registerSayCommand(command, autoCallback, 'AutoRoll the dice commands for players used by SuperDice.')

database = dataManager('addon_autoroll')

strings = stringsManager('addon_autoroll')
